package com.whj.serviceorder.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.whj.internalcommon.constant.CommonStatusEnum;
import com.whj.internalcommon.constant.DriverCarConstants;
import com.whj.internalcommon.constant.IdentityConstant;
import com.whj.internalcommon.constant.OrderConstants;
import com.whj.internalcommon.dto.Car;
import com.whj.internalcommon.dto.PriceRules;
import com.whj.internalcommon.dto.ResponseResult;
import com.whj.internalcommon.request.OrderRequest;
import com.whj.internalcommon.request.PriceRulesNewRequest;
import com.whj.internalcommon.request.PushRequest;
import com.whj.internalcommon.request.TraceTimeRequest;
import com.whj.internalcommon.response.OrderDriverResponse;
import com.whj.internalcommon.response.TerminalResponse;
import com.whj.internalcommon.response.TrsearchResponse;
import com.whj.internalcommon.utils.RedisTokenKeyUtils;
import com.whj.serviceorder.config.RedisConfig;
import com.whj.serviceorder.entity.OrderInfo;
import com.whj.serviceorder.mapper.OrderInfoMapper;
import com.whj.serviceorder.remote.ServiceDriverUserClient;
import com.whj.serviceorder.remote.ServiceMapClient;
import com.whj.serviceorder.remote.ServicePriceClient;
import com.whj.serviceorder.remote.ServiceSsmPushClient;
import com.whj.serviceorder.service.OrderInfoService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author whj
 * @since 2023-01-28
 */
@Service
@Slf4j
public class OrderInfoServiceImpl implements OrderInfoService {


    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private ServicePriceClient servicePriceClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ServiceDriverUserClient serviceDriverUserClient;

    @Autowired
    private ServiceMapClient serviceMapClient;

    @Autowired
    private RedisConfig redisConfig;

    @Autowired
    private ServiceSsmPushClient serviceSsmPushClient;


    /**
     * 乘客下单 添加订单信息
     * 乘客 id 和手机号 是由 api-passenger服务解析传给前端，前端发送过来
     *
     * @param orderRequest
     * @return
     */
    @Override
    public ResponseResult orderAdd(OrderRequest orderRequest) {

        //查询该城市是否有可用的司机
        ResponseResult<Boolean> availableDriver = serviceDriverUserClient.isAvailableDriver(orderRequest.getAddress());
        log.info("是否有司机：" + availableDriver.getData().toString());
        if (!availableDriver.getData()) {
            return ResponseResult.fail(CommonStatusEnum.CITY_DRIVER_EMPTY.getCode(), CommonStatusEnum.CITY_DRIVER_EMPTY.getValue());
        }

        //创建订单之前，判断计价规则是否是最新
        String fareType = orderRequest.getFareType();
        Integer fareVersion = orderRequest.getFareVersion();
        ResponseResult<Boolean> versionIsNew = servicePriceClient.getVersionIsNew(new PriceRulesNewRequest(fareType, fareVersion));
        if (!(versionIsNew.getData())) {
            return ResponseResult.fail(CommonStatusEnum.PRICE_RULE_NOT_NEW.getCode(), CommonStatusEnum.PRICE_RULE_NOT_NEW.getValue(), "");
        }

        // 判断需要下单的设备是否是黑名单设备
//        if (isBlackDevice(orderRequest)) {
//            return ResponseResult.fail(CommonStatusEnum.DEVICE_IS_BLACK.getCode(), CommonStatusEnum.DEVICE_IS_BLACK.getValue(), "");
//        }

        //判断：下单的城市和计价规则是否正常
        if (!isPriceRuleExists(orderRequest)) {
            return ResponseResult.fail(CommonStatusEnum.PRICE_RULE_NOT_NORMAL.getCode(), CommonStatusEnum.PRICE_RULE_NOT_NORMAL.getValue(), "");
        }

        //判断有正在进行的订单，不允许下单
        if (isPassengerGoingOn(orderRequest.getPassengerId()).size() > 0) {
            return ResponseResult.fail(CommonStatusEnum.ORDER_GOING_ON.getCode(), CommonStatusEnum.ORDER_GOING_ON.getValue());
        }
        //创建订单
        OrderInfo orderInfo = new OrderInfo();

        // 将 orderRequest 赋值给  orderInfo
        try {
            BeanUtils.copyProperties(orderInfo, orderRequest);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        orderInfo.setOrderStatus(OrderConstants.ORDER_START);

        LocalDateTime now = LocalDateTime.now();
        orderInfo.setCreateTime(now);
        orderInfo.setUpdateTime(now);

        orderInfoMapper.insert(orderInfo);

        for (int i = 1; i < 6; i++) {
            // 派单
            int result = dispatchRealTimeOrder(orderInfo);
            if (result == 1) {
                break;
            }
            if (result == 2){
                return ResponseResult.fail(CommonStatusEnum.CAR_VEHICLE_TYPE_EMPTY.getCode(),CommonStatusEnum.CAR_VEHICLE_TYPE_EMPTY.getValue(),"");
            }
            if (i == 5) {
                // 订单无效
                orderInfo.setOrderStatus(OrderConstants.ORDER_INVALID);
                orderInfoMapper.updateById(orderInfo);
            } else {
                // 等待20s
                try {
                    Thread.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return ResponseResult.success("");
    }

    /**
     * 实时派单逻辑
     *
     * @param orderInfo
     */
    public int dispatchRealTimeOrder(OrderInfo orderInfo) {

        log.info("循环找车一次");

        int result = 0;

        String depLatitude = orderInfo.getDepLatitude();
        String depLongitude = orderInfo.getDepLongitude();
        String center = depLatitude + "," + depLongitude;

        List<Integer> radiusList = new ArrayList<>();
        radiusList.add(2000);
        radiusList.add(4000);
        radiusList.add(5000);

        ResponseResult<List<TerminalResponse>> listResponseResult = null;
        // goto是为了测试。
        radius:
        for (int i = 0; i < radiusList.size(); i++) {
            int radius = radiusList.get(i);
            listResponseResult = serviceMapClient.aroundSearch(center, radius);
            log.info("在半径为" + radius + "的范围类，寻找车辆,结果：" + JSONArray.fromObject(listResponseResult.getData()).toString());

            //获得终端{"carId":1594231277809336325,"tid":"637704654"}

            //解析终端 根据解析出来的终端获取车辆信息
            List<TerminalResponse> data = listResponseResult.getData();
            //测试循环找车
            //List<TerminalResponse> data = new ArrayList<>();
            for (int j = 0; j < data.size(); j++) {

                TerminalResponse terminalResponse = data.get(j);
                Long carId = terminalResponse.getCarId();
                String latitude = terminalResponse.getLatitude();
                String longitude = terminalResponse.getLongitude();

                //查询是否有可用的司机
                ResponseResult<OrderDriverResponse> availableDriver = serviceDriverUserClient.getAvailableDriver(carId);
                if (availableDriver.getCode() == CommonStatusEnum.AVAILABLE_DRIVER_EMPTY.getCode()) {
                    log.info("没有对应出车的司机。");
                    continue;
                } else {
                    log.info("找到了正在出车的司机，司机ID为：" + carId);
                    OrderDriverResponse orderDriverResponse = availableDriver.getData();
                    Long driverId = orderDriverResponse.getDriverId();
                    String driverPhone = orderDriverResponse.getDriverPhone();
                    String vehicleTypeFromCar = orderDriverResponse.getVehicleType();

                    //判断车辆类型是否符合
                    String vehicleType = orderInfo.getVehicleType();
                    if (!vehicleType.trim().equals(vehicleTypeFromCar)) {
                        log.info("车辆类型不符合！");
                        result = 2;
                        continue;
                    }

                    //加锁
                    String lockKey = (driverId + "").intern();
                    RLock lock = redisConfig.redissonClient().getLock(lockKey);
                    lock.lock();

                    //判断司机是否有正在进行的订单
                    if (isDriverGoingOn(driverId) > 0) {
                        lock.unlock();
                        continue;
                    }

                    //订单直接匹配司机
                    //查询当前车辆信息
                    QueryWrapper<Car> carQueryWrapper = new QueryWrapper<>();
                    carQueryWrapper.eq("id", carId);

                    //设置订单中和司机车辆相关的信息
                    orderInfo.setDriverId(driverId);
                    orderInfo.setDriverPhone(driverPhone);
                    orderInfo.setCarId(carId);

                    //获取地图信息
                    orderInfo.setReceiveOrderCarLongitude(longitude);
                    orderInfo.setReceiveOrderCarLatitude(latitude);

                    orderInfo.setLicenseId(orderDriverResponse.getLicenseId());
                    orderInfo.setVehicleNo(orderDriverResponse.getVehicleNo());
                    orderInfo.setOrderStatus(OrderConstants.DRIVER_RECEIVE_ORDER);
                    orderInfo.setReceiveOrderTime(LocalDateTime.now());

                    orderInfoMapper.updateById(orderInfo);

                    //通知司机乘客的信息
                    JSONObject passengerMessage = new JSONObject();
                    passengerMessage.put("orderId",orderInfo.getId());
                    passengerMessage.put("passengerId", orderInfo.getPassengerId());
                    passengerMessage.put("passengerPhone", orderInfo.getPassengerPhone());
                    passengerMessage.put("departure", orderInfo.getDeparture());
                    passengerMessage.put("depLongitude", orderInfo.getDepLongitude());
                    passengerMessage.put("depLatitude", orderInfo.getDepLatitude());

                    passengerMessage.put("destination", orderInfo.getDestination());
                    passengerMessage.put("destLongitude", orderInfo.getDestLongitude());
                    passengerMessage.put("destLatitude", orderInfo.getDestLatitude());

                    PushRequest pushRequest = new PushRequest();
                    pushRequest.setUserId(driverId);
                    pushRequest.setIdentity(IdentityConstant.DRIVER_IDENTITY);
                    pushRequest.setContent(passengerMessage.toString());
                    serviceSsmPushClient.push(pushRequest);


                    //通知乘客司机的信息
                    JSONObject driverMessage = new JSONObject();
                    driverMessage.put("orderId", orderInfo.getId());
                    driverMessage.put("driverId", orderInfo.getDriverId());
                    driverMessage.put("driverPhone", orderInfo.getDriverPhone());
                    driverMessage.put("vehicleNo", orderInfo.getVehicleNo());
                    driverMessage.put("receiveOrderCarLatitude", orderInfo.getReceiveOrderCarLatitude());
                    driverMessage.put("receiveOrderCarLongitude", orderInfo.getReceiveOrderCarLongitude());
                    // 调用service-driver-user 服务获取车辆信息
                    ResponseResult<Car> carById = serviceDriverUserClient.getCarById(orderInfo.getCarId());
                    Car car = carById.getData();
                    driverMessage.put("vehicleNo", car.getVehicleNo());
                    driverMessage.put("brand", car.getBrand());
                    driverMessage.put("vehicleColor", car.getVehicleColor());

                    PushRequest pushRequest1 = new PushRequest();
                    pushRequest1.setUserId(orderInfo.getPassengerId());
                    pushRequest1.setIdentity(IdentityConstant.PASSENGER_IDENTITY);
                    pushRequest1.setContent(driverMessage.toString());

                    serviceSsmPushClient.push(pushRequest1);
                    result = 1;
                    //解锁
                    lock.unlock();

                    //退出，不在进行查找 如找到车辆，则跳出循环
                    break radius;
                }
            }
        }
        return result;
    }

    /**
     * 司机去接乘客
     *
     * @param orderRequest
     * @return
     */
    @Override
    public ResponseResult toPickUpPassenger(OrderRequest orderRequest) {
        //获取orderRequest中的信息
        Long orderId = orderRequest.getOrderId();
        String toPickUpPassengerAddress = orderRequest.getToPickUpPassengerAddress();
        String toPickUpPassengerLatitude = orderRequest.getToPickUpPassengerLatitude();
        String toPickUpPassengerLongitude = orderRequest.getToPickUpPassengerLongitude();
        LocalDateTime toPickUpPassengerTime = orderRequest.getToPickUpPassengerTime();
        //根据orderId更新数据
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", orderId);
        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);
        orderInfo.setToPickUpPassengerAddress(toPickUpPassengerAddress);
        orderInfo.setToPickUpPassengerLatitude(toPickUpPassengerLatitude);
        orderInfo.setToPickUpPassengerLongitude(toPickUpPassengerLongitude);
        orderInfo.setToPickUpPassengerTime(LocalDateTime.now());
        orderInfo.setOrderStatus(OrderConstants.DRIVER_TO_PICK_UP_PASSENGER);
        orderInfoMapper.updateById(orderInfo);
        return ResponseResult.success("");
    }

    /**
     * 司机到达接乘客的位置
     *
     * @param orderRequest
     * @return
     */
    @Override
    public ResponseResult arriveDeparture(OrderRequest orderRequest) {
        Long orderId = orderRequest.getOrderId();

        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", orderId);
        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);
        orderInfo.setDriverArrivedDepartureTime(LocalDateTime.now());
        //修改订单状态
        orderInfo.setOrderStatus(OrderConstants.DRIVER_ARRIVED_DEPARTURE);
        orderInfoMapper.updateById(orderInfo);
        return ResponseResult.success("");
    }

    /**
     * 司机接到乘客
     *
     * @param orderRequest
     * @return
     */
    @Override
    public ResponseResult pickUpPassenger(OrderRequest orderRequest) {
        Long orderId = orderRequest.getOrderId();
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", orderId);
        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);
        orderInfo.setPickUpPassengerTime(LocalDateTime.now());
        orderInfo.setPickUpPassengerLongitude(orderRequest.getPickUpPassengerLongitude());
        orderInfo.setPickUpPassengerLatitude(orderRequest.getPickUpPassengerLatitude());
        orderInfo.setOrderStatus(OrderConstants.PICK_UP_PASSENGER);
        orderInfoMapper.updateById(orderInfo);
        return ResponseResult.success("");
    }

    /**
     * 乘客达到目的地
     *
     * @param orderRequest
     * @return
     */
    @Override
    public ResponseResult passengerGetOff(OrderRequest orderRequest) {
        Long orderId = orderRequest.getOrderId();
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", orderId);
        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);

        orderInfo.setPassengerGetoffLatitude(orderRequest.getPassengerGetoffLatitude());
        orderInfo.setPassengerGetoffLongitude((orderRequest.getPassengerGetoffLongitude()));
        orderInfo.setPassengerGetoffTime(LocalDateTime.now());
        orderInfo.setOrderStatus(OrderConstants.PASSENGER_GETOFF);

        //订单行驶的路程和时间 调用service-map 的接口
        TraceTimeRequest traceTimeRequest = new TraceTimeRequest();
        ResponseResult<Car> carById = serviceDriverUserClient.getCarById(orderInfo.getCarId());
        traceTimeRequest.setTid(carById.getData().getTid());
        //将时间转化成毫秒值
        traceTimeRequest.setStartTime(orderInfo.getPickUpPassengerTime().toInstant(ZoneOffset.of("+8")).toEpochMilli());
        traceTimeRequest.setEndTime(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());

        //测试时，时间不跨度不能太大
        //traceTimeRequest.setEndTime(1677375330000l);
        log.info("时间和距离为：" + traceTimeRequest.toString());
        ResponseResult<TrsearchResponse> trsearch = serviceMapClient.trsearch(traceTimeRequest);
        //设置到orderInfo
        TrsearchResponse data = trsearch.getData();

        Long driverMile = data.getDriverMile();
        Long driverTime = data.getDriverTime();
        orderInfo.setDriveMile(driverMile);
        orderInfo.setDriveTime(driverTime);

        // 获取价格
        String address = orderInfo.getAddress();
        String vehicleType = orderInfo.getVehicleType();
        ResponseResult<Double> price = servicePriceClient.calculatePrice(driverMile.intValue(), driverTime.intValue(), address, vehicleType);
        orderInfo.setPrice(price.getData());

        orderInfoMapper.updateById(orderInfo);
        return ResponseResult.success("");
    }


    /**
     * 对订单支付完成
     *
     * @param orderRequest 订单id
     * @return
     */
    @Override
    public ResponseResult pay(OrderRequest orderRequest) {
        Long orderId = orderRequest.getOrderId();
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        orderInfo.setOrderStatus(OrderConstants.SUCCESS_PAY);
        orderInfoMapper.updateById(orderInfo);
        return ResponseResult.success("");
    }

    /**
     * 订单取消
     *
     * @param orderId  取消id
     * @param identity 取消的身份表示，1 乘客，2司机
     * @return
     */
    @Override
    public ResponseResult cancel(Long orderId, String identity) {

        //查询订单当前的状态
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        Integer orderStatus = orderInfo.getOrderStatus();

        LocalDateTime cancelTime = LocalDateTime.now();
        Integer cancelOperator = null;
        Integer cancelTypeCode = null;

        // 等于0表示取消失败
        int cancelType = 1;

        // 更新订单的状态为取消状态
        //乘客取消
        if (identity.trim().equals(IdentityConstant.PASSENGER_IDENTITY)) {
            switch (orderStatus) {
                // 订单开始
                case OrderConstants.ORDER_START:
                    cancelTypeCode = OrderConstants.CANCEL_PASSENGER_BEFORE;
                    break;
                //司机接到订单
                case OrderConstants.DRIVER_RECEIVE_ORDER:
                    LocalDateTime receiveOrderTime = orderInfo.getReceiveOrderTime();
                    long between = ChronoUnit.MINUTES.between(receiveOrderTime, cancelTime);
                    if (between > 1) {
                        cancelTypeCode = OrderConstants.CANCEL_PASSENGER_ILLEGAL;
                    } else {
                        cancelTypeCode = OrderConstants.CANCEL_PASSENGER_BEFORE;
                    }
                    break;
                //司机去接乘客
                case OrderConstants.DRIVER_TO_PICK_UP_PASSENGER:
                    //司机到达乘客起点
                case OrderConstants.DRIVER_ARRIVED_DEPARTURE:
                    cancelTypeCode = OrderConstants.CANCEL_PASSENGER_ILLEGAL;
                    break;
                default:
                    log.info("乘客取消失败!");
                    cancelType = 0;
                    break;
            }
        }
        //司机取消
        if (identity.trim().equals(IdentityConstant.DRIVER_IDENTITY)) {
            switch (orderStatus) {
                //司机接到订单
                case OrderConstants.DRIVER_RECEIVE_ORDER:
                    //司机去接乘客
                case OrderConstants.DRIVER_TO_PICK_UP_PASSENGER:
                    //司机到达乘客起点
                case OrderConstants.DRIVER_ARRIVED_DEPARTURE:
                    LocalDateTime receiveOrderTime = orderInfo.getReceiveOrderTime();
                    long between = ChronoUnit.MINUTES.between(receiveOrderTime, cancelTime);
                    if (between > 1) {
                        cancelTypeCode = OrderConstants.CANCEL_DRIVER_ILLEGAL;
                    } else {
                        cancelTypeCode = OrderConstants.CANCEL_DRIVER_BEFORE;
                    }
                    break;
                default:
                    log.info("乘客取消失败!");
                    cancelType = 0;
                    break;
            }
        }

        if (cancelType == 0) {
            return ResponseResult.fail(CommonStatusEnum.ORDER_CANCEL_ERROR.getCode(), CommonStatusEnum.ORDER_CANCEL_ERROR.getValue(),"");
        }

        orderInfo.setCancelTypeCode(cancelTypeCode);
        orderInfo.setCancelTime(cancelTime);
        orderInfo.setCancelOperator(Integer.parseInt(identity));
        orderInfo.setOrderStatus(OrderConstants.ORDER_CANCEL);

        orderInfoMapper.updateById(orderInfo);

        return ResponseResult.success("");
    }

    /**
     * 订单支付 修改订单的状态
     *
     * @param orderRequest
     * @return
     */
    @Override
    public ResponseResult pushPay(OrderRequest orderRequest) {
        Long orderId = orderRequest.getOrderId();
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        orderInfo.setOrderStatus(OrderConstants.TO_START_PAY);
        orderInfoMapper.updateById(orderInfo);
        return ResponseResult.success("");
    }

    /**
     * 订单详情
     */
    @Override
    public ResponseResult<OrderInfo> detail(Long orderId) {
        OrderInfo orderInfo =  orderInfoMapper.selectById(orderId);
        return ResponseResult.success(orderInfo);
    }

    @Override
    public ResponseResult<OrderInfo> current(String phone, String identity){
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();

        if (identity.equals(IdentityConstant.DRIVER_IDENTITY)){
            queryWrapper.eq("driver_phone",phone);

            queryWrapper.and(wrapper->wrapper
                    .eq("order_status",OrderConstants.DRIVER_RECEIVE_ORDER)
                    .or().eq("order_status",OrderConstants.DRIVER_TO_PICK_UP_PASSENGER)
                    .or().eq("order_status",OrderConstants.DRIVER_ARRIVED_DEPARTURE)
                    .or().eq("order_status",OrderConstants.PICK_UP_PASSENGER)

            );
        }
        if (identity.equals(IdentityConstant.PASSENGER_IDENTITY)){
            queryWrapper.eq("passenger_phone",phone);
            queryWrapper.and(wrapper->wrapper.eq("order_status",OrderConstants.ORDER_START)
                    .or().eq("order_status",OrderConstants.DRIVER_RECEIVE_ORDER)
                    .or().eq("order_status",OrderConstants.DRIVER_TO_PICK_UP_PASSENGER)
                    .or().eq("order_status",OrderConstants.DRIVER_ARRIVED_DEPARTURE)
                    .or().eq("order_status",OrderConstants.PICK_UP_PASSENGER)
                    .or().eq("order_status",OrderConstants.PASSENGER_GETOFF)
                    .or().eq("order_status",OrderConstants.TO_START_PAY)
            );
        }

        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);
        return ResponseResult.success(orderInfo);
    }


    /**
     * 判断是否有 业务中的订单 查询司机是否有正在进行中的订单
     *
     * @param driverId
     * @return
     */
    private int isDriverGoingOn(Long driverId) {
        //判断有正在进行的订单，不允许下单
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("driver_id", driverId);
        queryWrapper.and(wrapper -> wrapper.eq("order_status", OrderConstants.DRIVER_RECEIVE_ORDER)
                .or().eq("order_status", OrderConstants.DRIVER_TO_PICK_UP_PASSENGER)
                .or().eq("order_status", OrderConstants.DRIVER_ARRIVED_DEPARTURE)
                .or().eq("order_status", OrderConstants.PICK_UP_PASSENGER)
        );
        Integer validOrderNumber = orderInfoMapper.selectCount(queryWrapper);
        log.info("司机Id：" + driverId + ",正在进行的订单的数量：" + validOrderNumber);

        return validOrderNumber;
    }

    /**
     * 更具订单状态去判断是否能够创建新的订单
     *
     * @param passengerId
     * @return
     */
    private List<OrderInfo> isPassengerGoingOn(Long passengerId) {
        //判断有正在进行的订单，不允许下单
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("passenger_id", passengerId);
        queryWrapper.and(wrapper -> wrapper.eq("order_status", OrderConstants.ORDER_START)
                .or().eq("order_status", OrderConstants.DRIVER_RECEIVE_ORDER)
                .or().eq("order_status", OrderConstants.DRIVER_TO_PICK_UP_PASSENGER)
                .or().eq("order_status", OrderConstants.DRIVER_ARRIVED_DEPARTURE)
                .or().eq("order_status", OrderConstants.PICK_UP_PASSENGER)
                .or().eq("order_status", OrderConstants.PASSENGER_GETOFF)
                .or().eq("order_status", OrderConstants.TO_START_PAY)
        );

        List<OrderInfo> orderInfos = orderInfoMapper.selectList(queryWrapper);
        return orderInfos;
    }

    /**
     * 判断需要下单的设备是否是黑名单设备
     *
     * @param orderRequest
     * @return
     */
    private boolean isBlackDevice(OrderRequest orderRequest) {

        String deviceCode = orderRequest.getDeviceCode();
        //生成key
        String deviceCodeKey = RedisTokenKeyUtils.blackDeviceCodePrefix + deviceCode;

        //设置key，看看原来是否有key
        Boolean aBoolean = stringRedisTemplate.hasKey(deviceCodeKey);
        if (aBoolean) {
            String s = stringRedisTemplate.opsForValue().get(deviceCodeKey);
            int i = Integer.parseInt(s);
            if (i >= 2) {
                //当前设备超过下单次数
                return true;
            } else {
                stringRedisTemplate.opsForValue().increment(deviceCodeKey);
            }
        } else {
            stringRedisTemplate.opsForValue().setIfAbsent(deviceCodeKey, "1", 1L, TimeUnit.MINUTES);
        }
        return false;
    }

    /**
     * 根据城市编码和车辆代码来查询是否有计价规则 调用service-price 服务
     *
     * @param orderRequest
     * @return
     */
    private boolean isPriceRuleExists(OrderRequest orderRequest) {
        String cityCode = orderRequest.getAddress();
        String vehicleType = orderRequest.getVehicleType();
        PriceRules priceRules = new PriceRules();
        priceRules.setCityCode(cityCode);
        priceRules.setVehicleType(vehicleType);
        ResponseResult<Boolean> result = servicePriceClient.ifExists(priceRules);
        Boolean data = result.getData();
        if (data) {
            return true;
        } else {
            return false;
        }
    }
}
